import random
import time

from selenium import webdriver

from douyin.web import WebClient
from hualian.utils import user_agent_pc


class SeleniumClient:
    order_url = r'https://live.douyin.com/732581402354'

    def __init__(self):
        self.user_list = []
        self.chromeOptions = webdriver.ChromeOptions()
        self.agent = random.choice(user_agent_pc)
        # self.chromeOptions.add_argument('--headless')
        self.chromeOptions.add_argument('lang=zh_CN.UTF-8')
        # self.chromeOptions.add_argument('user-agent="%s"' % self.agent)
        self.browser = webdriver.Chrome(options=self.chromeOptions)
        self.browser.implicitly_wait(12)  # seconds
        self.webClient = WebClient()

    def go_url(self, url):
        # 清除浏览器cookies
        self.browser.delete_all_cookies()
        try:
            self.browser.get(url)
            for i in range(0, 100):
                self.uni_user_list()
        except Exception as e:
            print("请求超时__>>", e)
        finally:
            pass
            # self.quit()

    def uni_user_list(self):
        key_dict = {}
        res_list = []
        print("uni_user_list--start---")
        m_user_list = self.find_list()
        print("uni_user_list", m_user_list)
        cache_list = self.user_list + m_user_list
        for i in cache_list:
            key_dict[i['name']] = i['text']
        key_list = [i for i in key_dict.keys()]
        for i in key_list:
            res_list.append({"name": i, "text": key_dict[i]})
        self.webClient.clear_container()
        for user in res_list:
            self.webClient.add_user(user['name'], user['text'])
        self.user_list = res_list

    def find_list(self):
        try:
            new_user_list = []
            chat_list = self.browser.find_elements_by_class_name('webcast-chatroom___item')
            print("聊天数量", len(chat_list))
            if len(chat_list) <= 1: return []
            for index, chat_item in enumerate(chat_list):
                if index == len(chat_list) - 1: continue
                print("===================chat_item", index)
                chat_user = self.get_element(chat_item)
                if not chat_user: continue
                print("chat_user", chat_user)
                new_user_list.append({'name': chat_user['name'], 'text': chat_user['text']})
            return new_user_list
        except Exception as e:
            print("find_list查找错误", e)
            return []
        finally:
            time.sleep(5)

    def get_element(self, chat_item):
        try:
            print("--------------------chat_item0", chat_item)
            print("--------------------chat_item0", chat_item.get_attribute('innerHTML'))
            chat_item = chat_item.find_elements_by_tag_name('div')
            if len(chat_item) <= 0: return None
            chat_item = chat_item[0]
            print("--------------------chat_item1", chat_item.get_attribute("class"))
            chat_user = chat_item.find_elements_by_class_name('tfObciRM')
            if len(chat_user) <= 0: return None
            chat_user = chat_user[0]
            print("chat_user", chat_user.text)
            chat_item_parent = chat_item.find_elements_by_class_name('Wz8LGswb')
            if len(chat_item_parent) <= 0: return None
            chat_item_parent = chat_item_parent[0]
            print("chat_item2", chat_item_parent.get_attribute('innerHTML'))
            chat_content = chat_item_parent.find_elements_by_tag_name('span')
            if len(chat_content) <= 0: return None
            chat_content = chat_content[0]
            print("chat_content", chat_content.text)
            return dict({'name': chat_user.text, 'text': chat_content.text})
        except Exception as e:
            print("get_element查找错误", e)
            return None
        finally:
            # time.sleep(2)
            pass

    def quit(self):
        if self.browser: self.browser.quit()


if __name__ == '__main__':
    selenium = SeleniumClient()
    selenium.go_url(SeleniumClient.order_url)
